import { useEffect, useRef, useState } from "react"

function useCount(num = 30) {
    const [count, setCount] = useState(num)
    const [run, setRun] = useState(false)
    const ref = useRef()

    const countDown = () => {
        setRun(true)
        ref.current = setInterval(() => {
            setCount((count) => {
                let timer = count - 1
                if (timer <= 0) {
                    setRun(false)
                    setCount(num)
                    clearInterval(ref.current)
                }
                return timer
            })
        }, 1000)
    }

    useEffect(() => {
        return (() => {
            clearInterval(ref.current)
        })
    }, [])
    return { count, run, countDown }
}


export default useCount
